package com.epfresh.supplier.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;

import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseFragment;
import com.epfresh.api.global.DataManager;
import com.epfresh.api.global.MessageCentre;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.supplier.R;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.fragment.HomePageFragment;
import com.epfresh.supplier.fragment.*;
import com.epfresh.api.widget.tablayout.CommonTabLayout;
import com.epfresh.api.widget.tablayout.TabEntity;
import com.epfresh.api.widget.tablayout.listener.OnTabSelectListener;


import java.util.ArrayList;

public class HomeActivity extends BaseActivity implements OnTabSelectListener {

    private CommonTabLayout lyTab;
    private FragmentManager fragmentManager;
    private HomePageFragment sellFragment;
    private HomeNewFragment homeNewFragment;//工作台
    private HomeBuyerFragment buyFragment;
    public HomeBuyerNewFragment buyerFragmentNew;// TODO: 2019/7/2 暂时隐藏掉
    private BaseFragment mineFragment;
    private BaseFragment currentFragment;
    private int currentFragmentIndex;

    public boolean isActivityVisible;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (ApplicationHelper.getInstance().getUser().getAccess_token() == null) {
            onLogin();
        }
        if (savedInstanceState != null) {
            Fragment f = getSupportFragmentManager().findFragmentByTag(TAG_SELL_FRAGMENT);
            if (f != null && f instanceof HomeNewFragment) {
                homeNewFragment = (HomeNewFragment) f;
            }
            f = getSupportFragmentManager().findFragmentByTag(TAG_MINE_FRAGMENT);
            if (f != null && f instanceof MineFragment) {
                mineFragment = (BaseFragment) f;
            }
        }
        BaseApplication.isHomeActivityAlive = true;
        setContentView(R.layout.activity_home);
        fragmentManager = getSupportFragmentManager();
        //根据tag寻找fragment
        initFragment();
        //初始化view
        initView();
        //加载数据
        initData(savedInstanceState);
        ApplicationHelper.getInstance().isHomeActivityAlive = true;
        ApplicationHelper.getInstance().updateVersion(false, null);
        ApplicationHelper.getInstance().expiredTime();
        MessageCentre.getInstance().homeActivity = this;
        Log.e("第1个up", "75");
        updateBuyerStatusHome();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        Fragment f = getSupportFragmentManager().findFragmentByTag(TAG_SELL_FRAGMENT);
        if (f != null && f instanceof HomeNewFragment) {
            homeNewFragment = (HomeNewFragment) f;
        }
        f = getSupportFragmentManager().findFragmentByTag(TAG_MINE_FRAGMENT);
        if (f != null && f instanceof MineFragment) {
            mineFragment = (BaseFragment) f;
        }
        f = getSupportFragmentManager().findFragmentByTag(TAG_BUY_FRAGMENT);
//        if(f != null &&f instanceof HomeBuyerFragment){
//            buyFragment = (HomeBuyerFragment) f;
//        }
//        if(f != null &&f instanceof HomeBuyerNewFragment){
//            buyerFragmentNew = (HomeBuyerNewFragment) f;
//        }
        setIntent(intent);
        //退出并重新登录
        if ("login".equals(intent.getStringExtra(Constant.TYPE))) {

            //根据tag寻找fragment
            initFragment();
            //初始化view
            initView();
            //加载数据
            initData(null);
        }

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        DataManager.getInstance().isNoRefreshSell = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        isActivityVisible = true;
        MessageCentre.getInstance().homeActivity = this;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isActivityVisible = false;
        MessageCentre.getInstance().homeActivity = null;
    }

    @Override
    protected void onDestroy() {
        BaseApplication.isHomeActivityAlive = false;
        super.onDestroy();
    }

    private void initData(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            currentFragmentIndex = savedInstanceState.getInt(Constant.KEY_HOME_STATE_INDEX);
        }
        updatePageStatus(currentFragmentIndex);
    }

    @Override
    protected View getToolBar() {
        return null;
    }

    private void initView() {
        String[] mTitles = {"工作台", getString(R.string.mine_page)};
        int[] mIconUnSelectIds = {
                R.mipmap.tab_sale_unselect,
                R.mipmap.tab_mine_unselect};
        final int[] mIconSelectIds = {
                R.mipmap.tab_sale_select,
                R.mipmap.tab_mine_select};
        ArrayList<TabEntity> mTabEntities = new ArrayList<>();
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnSelectIds[i]));
        }
        lyTab = (CommonTabLayout) findViewById(R.id.ly_navigation);
        lyTab.setTabItemRes(R.layout.layout_tab_top);
        lyTab.setTabData(mTabEntities);
        lyTab.setOnTabSelectListener(this);
    }

    //当前选中的tab
    @Override
    public void onTabSelect(int position) {
        if (position == 0) {
            DataManager.getInstance().isSellPage = true;
            if (BaseApplication.getInstance().getMerchant() == null || BaseApplication.getInstance().getMerchant().getId() == null || BaseApplication.getInstance().getMerchant().isOuthSeller()) {
                updatePageStatus(position);
                // homeNewFragment.reqMerchantList();
                return;
            } else {
                lyTab.setCurrentTab(lyTab.getmLastTab());
                toast("还未开通该权限");
            }
            return;
        }
//        selectPage(position);
        updatePageStatus(position);
        if (position == 1 && mineFragment != null) {// TODO: 2019/7/2 pos暂时改为1
            ((MineFragment) mineFragment).updateCertStatus();
            ((MineFragment) mineFragment).updateUserProfile();
            DataManager.getInstance().isSellPage = false;
        }
    }

    //再次点击当前选中的tab
    @Override
    public void onTabReselect(int position) {
        if (position == 1 && mineFragment != null) {
            ((MineFragment) mineFragment).updateCertStatus();
            ((MineFragment) mineFragment).updateUserProfile();
        }
    }

    //根据tag寻找fragment
    public void initFragment() {
        homeNewFragment = (HomeNewFragment) fragmentManager.findFragmentByTag(Constant.TAG_HOME_FRAGMENT);
        mineFragment = (BaseFragment) fragmentManager.findFragmentByTag(Constant.TAG_MINE_FRAGMENT);
    }

    String TAG_SELL_FRAGMENT = "sellFragment";
    String TAG_MINE_FRAGMENT = "mineFragment";
    String TAG_BUY_FRAGMENT = "buyFragment";

    private void updatePageStatus(int position) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        if (homeNewFragment != null) {
            transaction.hide(homeNewFragment);
        }
        if (mineFragment != null) {
            transaction.hide(mineFragment);
        }

        if (position == 0) {
            if (homeNewFragment == null) {
                homeNewFragment = new HomeNewFragment();
                transaction.add(R.id.content, homeNewFragment, TAG_SELL_FRAGMENT);
            }
            transaction.show(homeNewFragment);
            currentFragment = homeNewFragment;
        } else if (position == 1) {// TODO: 2019/7/2 pos暂时改为1
            if (mineFragment == null) {
                mineFragment = new MineFragment();
                transaction.add(R.id.content, mineFragment, TAG_MINE_FRAGMENT);
            }
            transaction.show(mineFragment);
            currentFragment = mineFragment;

        }
        currentFragmentIndex = position;
        transaction.commit();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        //记录当前fragment的下标
        outState.putInt(Constant.KEY_HOME_STATE_INDEX, currentFragmentIndex);
        super.onSaveInstanceState(outState);
    }

    public void updateOrderCount() {
        if (homeNewFragment != null) {
//            sellFragment.mRedDotHttpLoad();
        }
    }

    public void updateBuyerStatus() {
        Log.e("getMerchant", BaseApplication.getInstance().getMerchant().getName() + BaseApplication.getInstance().getMerchant().getStoreName() + BaseApplication.getInstance().getMerchant().isOuthSeller() + BaseApplication.getInstance().getMerchant().isOuthBuyer());

        if (lyTab.getCurrentTab() == 2) {
            lyTab.setCurrentTab(2);
            onTabSelect(2);
            return;
        }
        if (lyTab.getCurrentTab() == 0) {
            if (BaseApplication.getInstance().getMerchant() == null || BaseApplication.getInstance().getMerchant().getId() == null || BaseApplication.getInstance().getMerchant().isOuthSeller()) {
                return;
            } else {
                if (BaseApplication.getInstance().getMerchant().isOuthBuyer()) {
                    lyTab.setCurrentTab(1);
                    onTabSelect(1);
                    return;
                } else {
                    int currentTab = lyTab.getCurrentTab();
                    if (currentTab == 2) {
                        return;
                    } else {
                        lyTab.setCurrentTab(2);
                        onTabSelect(2);
                        return;
                    }
                }
            }
        } else {
            if (BaseApplication.getInstance().getMerchant().isOuthBuyer()) {
                lyTab.setCurrentTab(1);
                onTabSelect(1);
                return;
            } else {
                if (BaseApplication.getInstance().getMerchant().isOuthSeller()) {
                    lyTab.setCurrentTab(0);
                    onTabSelect(0);
                    return;
                } else {
                    lyTab.setCurrentTab(2);
                    onTabSelect(2);
                    return;
                }
            }
        }
    }

    public void updateBuyerStatusHome() {
        lyTab.setCurrentTab(0);
        updatePageStatus(0);
    }



    private long exitTime = 0; // 系统退出时间
    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            toast("再按一次返回键，退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            super.onBackPressed();
        }
    }
}
